//
//  XDrefreshControl.swift
//  XDweibo
//
//  Created by HanXingda on 15/7/4.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import FFAutoLayout

class XDrefreshControl: UIRefreshControl {

    override init() {
        super.init()
        addSubview(refreshView)
        
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))
        //设置kvo，监听自己的frame
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //显示箭头标记
    private var showTipFlag = false
    //显示加载标记
    private var showLoadFlag = false
    //kvo方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //如果大于0就返回
        if frame.origin.y > 0 {
            return
        }
        //如果正在刷新就显示加载动画
        if refreshing && !showLoadFlag {
            refreshView.startAnimationg()
            showLoadFlag = true
            return
        }
        if frame.origin.y < -50 && !showTipFlag {
            showTipFlag = true
            refreshView.rotationTipIcon(showTipFlag)
        } else if frame.origin.y >= -50 && showTipFlag{
            showTipFlag = false
            refreshView.rotationTipIcon(showTipFlag)
        }
        
    }
    override func endRefreshing() {
        super.endRefreshing()
        
        // 关闭动画
        refreshView.stopAnimation()
        
        // 重设刷新标记
        showLoadFlag = false
    }

    //注销kvo
    deinit {
        
        removeObserver(self, forKeyPath: "frame")
    }
    
    //懒加载
    lazy var refreshView = XDRefreshView.refreshView()
}



class XDRefreshView: UIView {
    
    @IBOutlet weak var tipIcon: UIImageView!
    @IBOutlet weak var loadImage: UIImageView!
    @IBOutlet weak var tipView: UIView!
    
    class func refreshView() -> XDRefreshView {
        return NSBundle.mainBundle().loadNibNamed("XDrefresh", owner: nil, options: nil).last as! XDRefreshView
    }
    //旋转提示图标
    private func rotationTipIcon (clockWise: Bool){
        
        var angle = M_PI
        angle += clockWise ? -0.01 : 0.01
       
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, CGFloat(angle))
        }
    }
    
    //开始加载动画
    func startAnimationg() {
        tipView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        loadImage.layer.addAnimation(anim, forKey: nil)
    }
    //停止动画
    func stopAnimation() {
        loadImage.layer.removeAllAnimations()
        tipView.hidden = false
    }
    
}